package tr.edu.yildiz.ce.dap.amc.services.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.namespace.QName;

import tr.edu.yildiz.ce.dap.amc.services.AppAuthService;
import tr.edu.yildiz.ce.dap.amc.util.AuthenticationFailedException;
import tr.edu.yildiz.ce.dap.amc.util.ManagerConnectionException;
import tr.edu.yildiz.ce.dap.amc.ws.gen.AppManager;
import tr.edu.yildiz.ce.dap.amc.ws.gen.AppManagerWs;
import tr.edu.yildiz.ce.dap.amc.ws.gen.Application;
import tr.edu.yildiz.ce.dap.amc.ws.gen.ApplicationList;
import tr.edu.yildiz.ce.dap.amc.ws.gen.AuthException_Exception;
import tr.edu.yildiz.ce.dap.appagent.model.App;
import tr.edu.yildiz.ce.dap.appagent.service.DownloadService;

public class AppAuthServiceImpl implements AppAuthService {

	public void getApplications(String deployFolder ,String autoDeployFolder,String urlStr,String username,String password)  throws ManagerConnectionException,AuthenticationFailedException{
		URL url = null;
		try {
			url = new URL(urlStr);
		}catch (Exception e) {
			throw new ManagerConnectionException(e);
		}
		AppManager appManager = new AppManager(url, new QName("http://impl.ws.app_manager.ce.yildiz.edu.tr/", "appManager"));
		AppManagerWs appManagerWs = appManager.getAppManagerPort();
		ApplicationList applicationList =null ;
		try {
			applicationList = appManagerWs.listAvailableApplications(username,password);
		} catch (AuthException_Exception e1) {
			throw new AuthenticationFailedException(e1);
		}
		List<Application> applications = applicationList.getApplication();
		List<App> appList = new ArrayList<App>(); 
		for (Application application : applications) {
			try {
				if (application.isAutoDeploy())
					downloadDapXml(autoDeployFolder, application);
				else
					downloadDapXml(deployFolder, application);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	private void downloadDapXml(String proxyFolder ,Application application) throws Exception{
		String dapxmlPath =proxyFolder + "/" + application.getName() + ".dapxml";
		DownloadService.download(application.getUrl(), dapxmlPath);
	}

}
